using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Lidgren.Network;
using System.Net;

public class RemotePlayer : MonoBehaviour
{
	#region public

	public void Bind(Board board, AutoServer server)
	{
		if (board == null || server == null || server.Status != Lidgren.Network.NetPeerStatus.Running)
		{
			Debug.LogException(new System.Exception("Transfered board or server reference is null or server is not runing!"));
		}
		m_Board = board;
		m_Server = server;

		// Broadcasting action chains to all clients
		m_Board.onMainActionChain += (queue) =>
		{
			m_Server.SendObjectToAll(new BoardRemote.ActionQueue(queue, BoardRemote.ActionQueue.Type.Main), NetDeliveryMethod.ReliableOrdered);
		};
		m_Board.onNewActionChain += (queue) =>
		{
			m_Server.SendObjectToAll(new BoardRemote.ActionQueue(queue, BoardRemote.ActionQueue.Type.New), NetDeliveryMethod.ReliableOrdered);
		};

		// Sending moves from remote players to board
		m_Server.OverrideDataHandler(typeof(Board.Move), (message, data, instance) =>
		{
            string output = "";
            foreach (var pair in players)
            {
                output += pair.Key.ToString() + " - ID" + pair.Value.ToString();
            }
            Debug.Log(output);
			Board.Move move = (Board.Move)data;
			move.playerID = players[message.SenderEndPoint];
			m_Board.MakeSwap(move.x1, move.y1, move.x2, move.y2, move.playerID);
		});
	}

	public void RegisterPlayer(IPEndPoint endPoint, int id)
	{
        Debug.Log(endPoint + " ID" + id);
		players.Add(endPoint, id);
	}

	#endregion
	#region protected

	protected Board m_Board;
	protected AutoServer m_Server;
	protected Dictionary<IPEndPoint, int> players = new Dictionary<IPEndPoint,int>();

	protected void Update()
	{
		m_Server.DispatchMessages();
	}
	
	#endregion
}

